(function(obj) {

    if (typeof module !== 'undefined' && typeof exports === 'object' && define.cmd) {
        module.exports = obj;
    } else if (typeof define === 'function' && define.amd) {
        define(function() {
            return obj;
        });
    } else {
        window.WeekUnitTableViewer = obj;
    }

})((function($) {

    var weekUnitTableViewer = function(opt) {
        this.params = {
            uuid: getUuid(),
            container: '', //容器
            weeks: false, // 星期列表
            units: false,
            loadWeeksUrl: false,
            loadUnitsUrl: false,
            convertWeeksFunc: false, // 与loadWeeksUrl配合使用，用于通过ajax获取数据后，对数据进行转换的函数
            convertUnitsFunc: false // 与loadUnitsUrl配合使用，用于通过ajax获取数据后，对数据进行转换的函数
        };

        this.init(opt);
    };

    weekUnitTableViewer.prototype = {

        init: function(opt) {
            copyPropertyVal(opt, this.params);
        },

        render: function() {
            var _weeks = this.getWeeks();
            var _units = this.getUnits();

            var _html = '<div id="div_' + this.params.uuid + '" class="wut_container">';
            _html += '      <table class="wut_table" onselectstart="return false">';
            _html += '          <tr>';
            _html += '              <td>节次/星期</td>';
            for (var i = 0; i < _weeks.length; i++) {
                var _w = _weeks[i];
                _html += '          <td class="wut_fontsize13" data-role="weekOrUnit" data-week="' + _w.code + '">' + _w.name + '</td>';
            }
            _html += '           </tr>';

            for (var i = 0; i < _units.length; i++) {
                var _u = _units[i];
                _html += '      <tr>';
                _html += '              <td class="wut_fontsize13" data-role="weekOrUnit" data-unit="' + _u.code + '">' + _u.name + '</td>';
                for (var j = 0; j < _weeks.length; j++) {
                    _html += '          <td data-role="item" data-week="' + _weeks[j].code + '" data-unit="' + _u.code + '"></td>';
                }
                _html += '      </tr>';
            }

            _html += '      </table>';
            _html += '  </div>';

            $(this.params.container).html(_html);
        },


        setResults: function(results, afterFn) {
            $('#div_' + this.params.uuid).find('td[data-role="item"]').each(function() {
                var jobj = $(this);
                for (var i = 0; i < results.length; i++) {
                    if (results[i].unit === jobj.attr('data-unit') && results[i].week === jobj.attr('data-week')) {
                        jobj.addClass('wut_td_arrange').html(results[i].content);
                    }
                }
            });

            if (typeof afterFn === 'function') {
                afterFn();
            }
        },


        getWeeks: function() {
            // 如果参数带有weeks，则直接使用参数的weeks
            if (this.params.weeks)
                return this.params.weeks;
            // 如果参数中写了获取weeks的URL，则使用ajax获取相应的weeks
            if (this.params.loadWeeksUrl)
                return this.getAjaxWeeks();
            // 获取默认提供的weeks
            return this.getDefaultWeeks();
        },

        /**
         * 获取默认的星期
         */
        getDefaultWeeks: function() {
            return [{
                code: "1",
                name: "星期一"
            }, {
                code: "2",
                name: "星期二"
            }, {
                code: "3",
                name: "星期三"
            }, {
                code: "4",
                name: "星期四"
            }, {
                code: "5",
                name: "星期五"
            }, {
                code: "6",
                name: "星期六"
            }, {
                code: "7",
                name: "星期日"
            }];;
        },

        /**
         * 通过ajax获取星期
         */
        getAjaxWeeks: function() {
            var _this = this;
            var _weeks = [];
            $.ajax({
                url: this.params.loadWeeksUrl,
                cache: false,
                dataType: "json",
                type: "get",
                async: false,
                success: function(data) {
                    if (_this.params.convertWeeksFunc) {
                        _weeks = _this.params.convertWeeksFunc(data);
                    } else {
                        _weeks = data;
                    }
                }
            });
            return _weeks;
        },

        getUnits: function() {
            // 如果参数带有units，则直接使用参数的units
            if (this.params.units)
                return this.params.units;
            // 如果参数中写了获取units的URL，则使用ajax获取相应的units
            if (this.params.loadUnitsUrl)
                return this.getAjaxUnits();
            // 获取默认提供的weeks
            return this.getDefaultUnits();
        },

        /**
         * 通过ajax获取节次
         */
        getAjaxUnits: function() {
            var _this = this;
            var _units = [];
            $.ajax({
                url: this.params.loadUnitsUrl,
                cache: false,
                dataType: "json",
                type: "get",
                async: false,
                success: function(data) {
                    if (_this.params.convertUnitsFunc) {
                        _units = _this.params.convertUnitsFunc(data);
                    } else {
                        _units = data;
                    }
                }
            });
            return _units;
        },

        /**
         * 获取默认的节次
         */
        getDefaultUnits: function() {
            return [{
                code: "1",
                name: "第1-2节"
            }, {
                code: "2",
                name: "第2-3节"
            }, {
                code: "3",
                name: "第4-5节"
            }, {
                code: "4",
                name: "第5-6节"
            }, {
                code: "5",
                name: "第7-8节"
            }];
        }

    };


    /**
     * 参数复制
     * @param from
     * @param to
     */
    function copyPropertyVal(from, to) {
        for (var f in from) {
            for (var t in to) {
                if (f === t && from[f] !== undefined) {
                    to[t] = from[f];
                    break;
                }
            }
        }
    }

    /**
     * 获取uuid
     * @returns {string}
     */
    function getUuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = "";

        var uuid = s.join("");
        return uuid;
    }

    return weekUnitTableViewer;

}(jQuery)));
